package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;

import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;


/**
 * 订单服务impl
 *
 * @author wangxin213
 * @date 2023/03/06
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newFixedThreadPool(100);

    private static final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    public static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<Long>();
        // lua脚本将库存判断，是否下单判断，发送订单到消息队列，定义为原子性操作
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        // 设置返回类型，与lua脚本return值保持一致
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ISeckillVoucherService iSeckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;

    private IVoucherOrderService proxy =null;

    /**
     * 同步秒杀，阻塞编程，性能较慢
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //初始化代理对象
        proxy= (IVoucherOrderService) AopContext.currentProxy();
        // 判断购买资格
        SeckillVoucher seckillVoucher = seckillVoucherMapper.selectById(voucherId);
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始！");
        }

        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束！");
        }

        if (seckillVoucher.getStock() < 1) {
            return Result.fail("库存不足！");
        }
        User user = UserHolder.getUser();
        SimpleRedisLock lock = new SimpleRedisLock();
        // 锁持有的时间必须大于业务代码执行时间
        // 防止一个用户多次下单
        boolean isLock = lock.tryLock("order:" + user.getId(), 30L, TimeUnit.SECONDS);
        if (!isLock) {
            return Result.fail("不允许重复下单");
        }
        // 正常拿锁失败需要自旋拿锁,最多自旋10次
        int count=0;
        while (true){
            if (count==10){
                return Result.fail("抢单的人太多了，下单失败");
            }
            // 对优惠卷加锁
            boolean isVoucherLock = lock.tryLock("order:" + voucherId, 30L, TimeUnit.SECONDS);
            if (isVoucherLock){
                break;
            }
            count++;
        }

        try {
            VoucherOrder order = new VoucherOrder();
            order.setId(voucherId);
            order.setUserId(user.getId());
            order.setId(redisIdWorker.createId("order"));
            // 拿到锁，进行订单创建，避免事务失效，需要拿到代理对象去调用createOrder
            return proxy.createVoucherOrder(order);
        } finally {
            // 释放锁，不能释放其他jvm线程持有的锁
            // 可能因为网络波动，导致业务代码时间过长，锁已经过期释放了
            lock.unlock("order:" + user.getId());
            lock.unlock("order:" + voucherId);

        }
    }

    /**
     * 创建优惠卷订单
     *
     * @param voucherOrder
     * @return
     */
    @Override
    @Transactional
    public Result createVoucherOrder(VoucherOrder voucherOrder) {

        //再次判断是否已经购买。用户一段时间后可能二次购买
        Long voucherId = voucherOrder.getVoucherId();
        int count = query().eq("user_id", voucherOrder.getUserId()).eq("voucher_id", voucherId).count();
        if (count > 0) {
            // 用户已经购买过了
            return Result.fail("用户已经购买过一次！");
        }
        //1、执行扣减秒杀卷库存,考虑了并发导致库存超卖的情况
        boolean update = iSeckillVoucherService.update().setSql("stock=stock-1")
                .eq("voucher_id", voucherId).gt("stock", 0).update();
        if (!update) {
            //扣减库存
            return Result.fail("库存不足！");
        }
        //2、新增订单

        save(voucherOrder);
        return Result.ok(voucherOrder);
    }

    /**
     * 异步秒杀--阻塞队列开启异步线程处理
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucherAsync(Long voucherId) throws InterruptedException {
        //初始化代理对象,启动类需要添加@EnableAspectJAutoProxy注解
        proxy= (IVoucherOrderService) AopContext.currentProxy();
        //获取用户
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.createId("order:");
        Long execute = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString(), orderId + "");
        if (execute == null) {
            throw new RuntimeException("seckill.lua执行失败");
        }
        if (execute == 1) {
            throw new RuntimeException("库存不足");
        } else if (execute == 2) {
            throw new RuntimeException("重复下单");
        }
        //TODO 保存voucherOrder阻塞队列
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        // 放入阻塞队列
//        orderTasks.put(voucherOrder);
        return Result.ok(orderId);
    }

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        // 阻塞队列处理
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
        // MQ处理
         SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandlerByMQ());
    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //1.获取用户,这里一定不能从UserHolder中取，取不到，因为现在所处的不是主线程
                    Long userId = voucherOrder.getUserId();
                    // 2.创建锁对象
                    RLock redisLock = redissonClient.getLock("lock:order:" + userId);
                    // 3.尝试获取锁(其实这里不需要拿锁，因为已经经过lua脚本的判断)，主要演示Redisson的使用,起到兜底
                    boolean isLock = redisLock.tryLock(1, 10, TimeUnit.SECONDS);
                    // 4.判断是否获得锁成功
                    if (!isLock) {
                        // 获取锁失败，直接返回失败或者重试
                        log.error("不允许重复下单！");
                        return;
                    }
                    try {

                        // AopContext.currentProxy()获取代理对象也是通过ThreadLocal获取的，子线程是拿不到的
                        proxy.createVoucherOrder(voucherOrder);
                    } finally {
                        // 释放锁
                        redisLock.unlock();
                    }
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    /**
     * 订单新增通过mq
     *
     * @author wangxin213
     * @date 2023/03/08
     */
    private class VoucherOrderHandlerByMQ implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    // 从消息队列中读取消息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            // 规定消费者为g1组下的c1消费者
                            Consumer.from("g1", "c1"),
                            // 定义读取规则--每次读一个，读不到就block2秒
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            // 定义读取的队列--读最新未被消费的msg
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    // 读不到接着读
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                    }
                    // 处理消息，创建订单，MapRecord本质为map，String是消息的id，第二个参数为消息的key，第三个为消息的value
                    MapRecord<String, Object, Object> map = list.get(0);
                    Map<Object, Object> value = map.getValue();
                    // 将消息的key-value装到bean里
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    proxy.createVoucherOrder(voucherOrder);
                    // ack
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", map.getId());
                } catch (IllegalStateException e) {
                    log.error("处理订单异常", e);
                    //处理异常消息
                    handlePendingList();
                }
            }
        }

        /**
         * 处理pending中的消费失败的消息
         */
        private void handlePendingList() {
            while (true) {
                try {
                    // 从消息队列中读取消息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            // 从最开始的开始读
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    if (CollectionUtils.isEmpty(list)) {
                        break;
                    }
                    // 处理消息，创建订单
                    MapRecord<String, Object, Object> map = list.get(0);
                    Map<Object, Object> value = map.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效
                    // 同样需要拿到代理对象
                    IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
                    proxy.createVoucherOrder(voucherOrder);
                    // ack，从pending中删除掉该消息，
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", map.getId());
                } catch (IllegalStateException e) {
                    // 处理失败继续进入while循环继续处理pending中的消息
                    log.error("处理订单异常", e);
                }
            }
        }
    }


}
